<template>
  <div>
    <Header title="栏目管理" />
    <h2>点击删除以下频道</h2>
    <div class="activeList">
      <div
        class="item"
        v-for="(category, index) in activeList"
        :key="index"
        @click="deactive(index)"
      >
        {{ category.name }}
      </div>
    </div>
    <h2>点击添加以下频道</h2>
    <div class="deactiveList">
      <div
        class="item"
        v-for="(category, index) in deactiveList"
        :key="index"
        @click="active(index)"
      >
        {{ category.name }}
      </div>
    </div>
  </div>
</template>

<script>
import Header from "../../components/CommonHeader";
export default {
  data() {
    return {
      activeList: [],
      deactiveList: [],
    };
  },
  components: {
    Header,
  },
  watch: {
    activeList() {
      localStorage.setItem("active", JSON.stringify(this.activeList));
    },
    deactiveList() {
      localStorage.setItem("deactive", JSON.stringify(this.deactiveList));
    },
  },
  created() {
    if (localStorage.getItem("active")) {
      this.activeList = JSON.parse(localStorage.getItem("active"));
      if (localStorage.getItem("deactive")) {
        this.deactiveList = JSON.parse(localStorage.getItem("deactive"));
      }
    } else {
      // 默认情况下是直接从远程拿数据,
      // 但是如果本地已经有储存了
      // 应该使用本地数据而不是远程响应
      this.$axios({
        url: "/category",
      }).then((res) => {
        console.log(res.data);
        this.activeList = res.data.data;
      });
    }
  },

  methods: {
    deactive(index) {
      if (this.activeList.length == 1) {
        this.$toast("最少留一个栏目");
        return;
      }

      // 将点击的已激活项目动到禁用数组中
      // 2. 放入新数组(先push再删, 不然旧数据就丢失)
      this.deactiveList.push(this.activeList[index]);
      // 1. 原来的地方删掉
      this.activeList.splice(index, 1);
    },
    active(index) {
      this.activeList.push(this.deactiveList[index]);
      this.deactiveList.splice(index, 1);
    },
  },
};
</script>

<style lang="less" scoped>
h2 {
  font-size: 13/360 * 100vw;
  font-weight: normal;
  color: #696969;
  padding-left: 20/360 * 100vw;
}
.activeList,
.deactiveList {
  display: flex;
  flex-wrap: wrap;
  padding: 10/360 * 100vw;
  .item {
    border: 1px solid #e4e4e4;
    padding: 0 13/360 * 100vw;
    margin: 10/360 * 100vw;
    font-size: 18/360 * 100vw;
    line-height: 35/360 * 100vw;
  }
}
</style>